#!/usr/bin/python
# coding:utf-8

'test TCP server'

from socket import *
from time import ctime
import select
import sys

HOST = ''
PORT = 22567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
input = [tcpSerSock, sys.stdin]  # input是一个列表，初始有欢迎套接字以及标准输入

while True:
    # 从input中选择，轮流处理client的请求连接（tcpSerSock），client发送来的消息(tcpCliSock)，及服务器端的发送消息(stdin)
    readyInput, readyOutput, readyException = select.select(input, [], [])
    for readySocket in readyInput:
        if readySocket == tcpSerSock:  # 新客户端加入
            print 'new client connection coming...'
            tcpCliSock, addr = tcpSerSock.accept()
            print '...connected from:', addr
            input.append(tcpCliSock)  # 将服务套接字加入到input列表中
        elif readySocket == sys.stdin:  # 处理服务器端的发送消息
            data = raw_input('>')
            if data == '88':
                tcpCliSock.send('%s' % (data))
                input.remove(tcpCliSock)
                break
            tcpCliSock.send('[%s] %s' % (ctime(), data))
        else: # 处理client发送来的消息
            data = readySocket.recv(BUFSIZ)
            print "recv from client =",data
            if data == '88':
                input.remove(readySocket)
                break

tcpSerSock.close()
